extends Node2D

enum Direction {LEFT=-1, RIGHT=1}

export(Direction) var direction = Direction.LEFT

onready var e: RigidBody2D = $"e!"
onready var m: RigidBody2D = $"m!"
onready var o: RigidBody2D = $"o!"

onready var sensor: Area2D = $"m!/Sensor"

const speed := 10

var time = 0
var num = 0

var e_dead = false
var m_dead = false
var o_dead = false

func _process(delta: float) -> void:
	
	var bodies = sensor.get_overlapping_bodies()
	if not bodies.empty():
		var player: RigidBody2D = bodies[0]
		direction = Direction.RIGHT if m.global_position.x < player.global_position.x else Direction.LEFT
	
	if m_dead:
		e_dead = true
		o_dead = true
		e.name = "dead"
		o.name = "dead"

	if not e_dead:
		e.angular_velocity = -e.rotation * speed
	if not m_dead:
		m.angular_velocity = -m.rotation * speed
	if not o_dead:
		o.angular_velocity = -o.rotation * speed
	
	
	time += delta
	if time > 0.01:
		num += 1
		num %= 100
		time = 0
		
		if direction == Direction.LEFT:
			if num > 40:
				if not o_dead and not m_dead:
					o.linear_velocity = (m.global_position - o.global_position) * speed
			elif num > 10:
				if not e_dead and not m_dead:
					e.linear_velocity = (m.global_position - e.global_position) * speed
			match num:
				1:
					if not e_dead and not m_dead:
						e.linear_velocity.x -= 4000
						m.linear_velocity.y = -speed * 150
				10:
					if not m_dead:
						m.linear_velocity.x -= 4000
				40:
					if not o_dead:
						o.linear_velocity.x -= 4000
		else:
			if num > 40:
				if not e_dead and not m_dead:
					e.linear_velocity = (m.global_position - e.global_position) * speed
			elif num > 10:
				if not o_dead and not m_dead:
					o.linear_velocity = (m.global_position - o.global_position) * speed
				
			match num:
				1:
					if not o_dead and not m_dead:
						o.linear_velocity.x += 4000
						m.linear_velocity.y = -speed * 150
				10:
					if not m_dead:
						m.linear_velocity.x += 4000
				40:
					if not e_dead:
						e.linear_velocity.x += 4000
			
func is_hurt_name(name: String):
	return 	"子弹" in name or\
		"大" == name or\
		"电" == name or\
		"人" == name

func _on_e_body_entered(body: Node) -> void:
	if is_hurt_name(body.name):
		e_dead = true
		e.name = "dead"


func _on_m_body_entered(body: Node) -> void:
	if is_hurt_name(body.name):
		m_dead = true
		m.name = "dead"


func _on_o_body_entered(body: Node) -> void:
	if is_hurt_name(body.name):
		o_dead = true
		o.name = "dead"
